from flask import Flask, render_template
import sys
import os
import threading

print("本版本正在开发中，这些内容可能包含致命错误，请谨慎使用！")
testcontent = False
def clear_screen():
    if os.name == 'nt': # Windows 系统
        os.system('cls')
    else: # Mac 和 Linux 系统
        os.system('clear')
def run():
    clear_screen()
    print("GavaScript-Web服务端已启动，端口:" + str(variable["port"]))
    if testcontent == True:
        print("已在本会话启用开发中的内容，这些内容可能包含致命错误，请谨慎使用。")
code = sys.argv
code.pop(0)
for r in code:
    wei = code.index(r)
    if ";" in r:
        code.pop(wei)
        for w in r.split(";"):
            code.insert(wei, w)
            wei += 1
variable = {"port":5000,"template":"templates","file":"index.html","default_inf":"<h1>GavaScript-Web生成的默认页面</h1>","error":f"[error]"}
for i in code:
    if i == "web.run()":
        app = Flask("gsw", template_folder=variable["template"])
        if os.path.exists(variable["template"] + '/' + variable["file"]):
            @app.route('/')
            def hello_world():

                return render_template(variable["file"])
        else:
            @app.route('/')
            def hello_world():
                return variable["default_inf"]


        @app.errorhandler(Exception)
        def handle_exception(error):
            # 处理所有异常
            variable["error"].replace("[error]",str(error),99999)
            return variable["error"], 500
        flask_thread = threading.Thread(target=run)
        flask_thread.start()
        app.run(port=variable["port"])
    elif "web.port" in i:
        variable["port"] = int(i[9:-1])
    elif "web.template_folder" in i:
        variable["template"] = i[20:-1]
    elif ".content(test=true)" == i or ".content(test=True)" == i:
        testcontent = True
        print("已在本会话启用开发中的内容，这些内容可能包含致命错误，请谨慎使用。")
    elif "web.index_file" in i:
        variable["file"] = i[15:-1]
    elif "web.default_inf" in i:
        variable["default_inf"] = i[16:-1]
    elif "web.error" in i:
        variable["error"] = i[10:-1]
    elif ".41" == i:
        print("已在本会话启用特殊内容“超级更新”")